# coding=utf-8
from django.shortcuts import render


class Menu(object):
    def __init__(self, title, url=None, parent=None, perms=()):
        self.title = title
        self.url = url
        self.sub_menus = []
        self.perms = perms
        self.parent = parent

        if parent is not None:
            parent.add_sub_menu(self)

    def add_sub_menu(self, menu):
        self.sub_menus.append(menu)
        menu.parent = self

    def set_selected(self, *titles):
        setattr(self, 'selected', True)
        if len(titles) <= 0:
            return

        title = titles[0]
        for s in self.sub_menus:
            if s.title == title:
                setattr(s, "selected", True)
                self.set_selected(*titles[1:])
            else:
                setattr(s, "selected", False)

    def clone(self):
        p = Menu(title=self.title, url=self.url, perms=self.perms)
        for m in self.sub_menus:
            nm = m.clone()
            p.add_sub_menu(nm)

        return p

def menu(title, url, perms=None, subs=()):
    m = Menu(title, url, perms=perms)
    for s in subs:
        m.add_sub_menu(s)
    return m


def set_menu_selected(menus, *titles):
    if titles is None:
        return

    title = titles[0]
    for m in menus:
        if m.title == title:
            m.set_selected(*titles[1:])


def html_render_ex(request, page, ctx, selected=None):
    mlist = []

    def has_perm(user, m):
        if m.perms is None:
            return True

        if user.has_perms(m.perms):
            return True

    def set_menu(user, menus):
        for m in menus:
            if not has_perm(user, m):
                menus.remove(m)
            else:
                set_menu(user, m.sub_menus)


    global menus
    for m in menus:
        mlist.append(m.clone())

    set_menu(request.user, mlist)

    set_menu_selected(mlist, *selected)
    ctx.update({"menus": mlist})

    return render(request, page, ctx)

menus = []